"use client";
import { useTranslations } from 'next-intl';
import { usePathname, useRouter } from 'next/navigation';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Globe, LogOut, Loader2, Menu, Search, ChartBarBig, Lightbulb, Wallet, Users } from 'lucide-react';
import { ThemeToggle } from './theme-toggle';
import Link from 'next/link';
import { signOut, getUser } from '@/controller/auth';
import { useEffect, useState } from 'react';
import { toast } from "sonner";
// Sidebar component props
interface SidebarProps {
  className?: string;
  locale: string;
}

// 导航项类型定义
export type NavItem = {
  id: string;
  href: string;
  icon: React.ReactElement;
  label: string;
};

export function Sidebar({
  className,
  locale
}: SidebarProps) {
  const logout = async () => {
    try {
      const { error } = await signOut();
      if (error) {
        console.error('Login failed:', error);
        toast.error('Login failed', {
          description: error.message
        });
      } else {
        toast.success('Login successfully logged out');
        // 退出登录成功，重定向到登录页面
        window.sessionStorage.removeItem('userInfo');
        router.push(`/${locale}/auth`);
      }
    } catch (err) {
      console.error('Login failed:', err);
    }
  }
  const [userProfile, setUserProfile] = useState({
    avatar_url: null,
    username: "loading..."
  })
  useEffect(() => {
    const getUserInfo = async () => {
      const user = await getUser()
      if (!user) {
        await logout()
        return
      }
      setUserProfile({
        avatar_url: null,
        username: user.email ? user.email.split('@')[0] : ""
      })
    }
    getUserInfo();
  }, []);
  // Get user initials for avatar fallback
  const getUserInitials = () => {
    if (userProfile?.username) {
      return userProfile.username.substring(0, 2).toUpperCase();
    }
    return 'U';
  };
  // 获取当前路径，用于高亮显示当前页面
  const pathname = usePathname();
  // 获取翻译
  const t = useTranslations('Navigation');
  const commonT = useTranslations('common');
  const [collapsed, setCollapsed] = useState(false);
  const router = useRouter();
  const [showLanguageSelect, setShowLanguageSelect] = useState(false);
  const [isChangingLanguage, setIsChangingLanguage] = useState(false);

  // 预加载另一种语言的翻译文件
  useEffect(() => {
    // 仅在客户端执行
    if (typeof window !== 'undefined') {
      // 创建一个隐藏的链接，预加载另一种语言的首页
      const preloadLocale = locale === 'en' ? 'zh' : 'en';
      const link = document.createElement('link');
      link.rel = 'prefetch';
      link.href = `/${preloadLocale}`;
      document.head.appendChild(link);

      return () => {
        document.head.removeChild(link);
      };
    }
  }, [locale]);

  // 切换语言的函数
  const changeLanguage = (targetLocale: string) => {
    // 如果已经在切换中，则不重复切换
    if (isChangingLanguage) return;

    // 设置加载状态
    setIsChangingLanguage(true);
    setShowLanguageSelect(false);

    // 获取当前路径
    const currentPath = pathname;

    // 从路径中移除当前语言前缀
    let newPath = currentPath;
    if (currentPath.startsWith(`/${locale}`)) {
      newPath = currentPath.substring(locale.length + 1);
    }

    // 如果路径为空，设置为根路径
    if (!newPath) {
      newPath = '/';
    }

    // 构建新路径
    const newUrl = `/${targetLocale}${newPath.startsWith('/') ? newPath : `/${newPath}`}`;

    // 使用更高效的方式加载新页面
    if (typeof window !== 'undefined') {
      // 仅在客户端执行
      const xhr = new XMLHttpRequest();
      xhr.open('GET', newUrl, true);
      xhr.onload = () => {
        window.location.href = newUrl;
      };
      xhr.onerror = () => {
        // 如果预请求失败，直接跳转
        window.location.href = newUrl;
      };
      xhr.send();
    }
  };

  // 切换下拉菜单显示状态
  const toggleLanguageSelect = () => {
    setShowLanguageSelect(!showLanguageSelect);
  };

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.language-select-container')) {
        setShowLanguageSelect(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  const navItems = [
    {
      id: 'search',
      href: '/',
      icon: <Search className="h-4 w-4" />,
      label: t('search'),
    },
    {
      id: 'project',
      href: '/project',
      icon: <ChartBarBig className="h-4 w-4" />,
      label: t('project'),
    },
    {
      id: 'leads',
      href: '/leads',
      icon: <Lightbulb className="h-4 w-4" />,
      label: t('leads'),
    },
    {
      id: 'team',
      href: '/team',
      icon: <Users className="h-4 w-4" />,
      label: t('team'),
    },
    {
      id: 'billing',
      href: '/billing',
      icon: <Wallet className="h-4 w-4" />,
      label: t('billing'),
    }
  ];
  // 处理导航项高亮
  useEffect(() => {
    // 仅在客户端执行
    if (typeof window === 'undefined') return;

    const handleNavHighlighting = () => {
      const items = document.querySelectorAll('[data-href]');

      items.forEach(item => {
        const href = item.getAttribute('data-href');
        if (!href) return;

        const isActive = pathname === href || pathname.startsWith(href + '/');

        // 添加或移除激活样式
        if (isActive) {
          item.classList.add('bg-gray-100', 'dark:bg-gray-800', 'text-gray-900', 'dark:text-white', 'rounded-md');
        } else {
          item.classList.remove('bg-gray-100', 'dark:bg-gray-800', 'text-gray-900', 'dark:text-white');
          item.classList.add('text-gray-600', 'dark:text-gray-400', 'hover:bg-gray-50', 'dark:hover:bg-gray-800', 'hover:text-gray-900', 'dark:hover:text-white', 'rounded-md');
        }
      });
    };

    // 初始化时执行一次
    handleNavHighlighting();

    // 添加事件监听器，确保在DOM更新后重新检查
    const observer = new MutationObserver(handleNavHighlighting);
    observer.observe(document.body, { childList: true, subtree: true });

    return () => observer.disconnect();
  }, [pathname]);

  return (
    <div className={cn(
      "flex flex-col h-full bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-800 transition-all duration-300",
      collapsed ? "w-16" : "w-50",
      className
    )}>
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800">
        {!collapsed && <h2 className="text-sm font-bold">{commonT('appName')}</h2>}
        <button
          onClick={() => setCollapsed(!collapsed)}
          className="p-1 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800"
          aria-label={collapsed ? "Expand menu" : "Collapse menu"}
        >
          <Menu size={20} />
        </button>
      </div>

      <nav className="flex-1 py-4 overflow-hidden">
        <ul className="space-y-1 px-2">
          {navItems.map((item) => {
            const isActive = pathname === item.href || pathname.startsWith(item.href + '/');

            return (
              <li key={item.id}>
                <Link
                  href={item.href}
                  className={cn(
                    "flex items-center rounded-md transition-colors text-sm",
                    collapsed ? "justify-center py-3 px-2" : "py-2 px-3",
                    isActive
                      ? "bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white"
                      : "text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-white"
                  )}
                  title={collapsed ? item.label : undefined}
                >
                  <span className={collapsed ? "" : "mr-3"}>{item.icon}</span>
                  {!collapsed && <span>{item.label}</span>}
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>

      <div className={cn(
        "mt-auto flex flex-col gap-2",
        "border-t border-gray-200 dark:border-gray-800",
        collapsed ? "p-2" : "p-4"
      )}>
        {/* 主题和语言切换按钮行 */}
        <div className={cn(
          "flex mb-3 ml-2",
          collapsed ? "flex-col space-y-2 items-center" : "items-center space-x-2"
        )}>
          {/* 主题切换按钮 */}
          <ThemeToggle collapsed={collapsed} />

          {/* 语言切换按钮 */}
          <div className="relative language-select-container">
            <button
              onClick={toggleLanguageSelect}
              disabled={isChangingLanguage}
              className="cursor-pointer border flex items-center justify-center p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors rounded-md"
              title={t('language')}
            >
              {isChangingLanguage ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Globe className="h-4 w-4" />
              )}
            </button>

            {/* 语言选择下拉菜单 */}
            {showLanguageSelect && (
              <div
                className="absolute z-50 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg py-1"
                style={{
                  width: '120px',
                  left: collapsed ? '40px' : '0px',
                  bottom: collapsed ? '-18%' : '100%',
                  marginBottom: '4px',
                  overflow: 'hidden'
                }}
              >
                <div className="flex flex-col">
                  <button
                    onClick={() => changeLanguage('en')}
                    className={cn(
                      "w-full text-left px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-800",
                      locale === 'en' ? "bg-gray-100 dark:bg-gray-800 font-medium" : ""
                    )}
                  >
                    English
                  </button>
                  <button
                    onClick={() => changeLanguage('zh')}
                    className={cn(
                      "w-full text-left px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-800",
                      locale === 'zh' ? "bg-gray-100 dark:bg-gray-800 font-medium" : ""
                    )}
                  >
                    中文
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className={cn(
          "flex items-center pl-2",
          collapsed ? "justify-center" : ""
        )}>
          <Avatar className="h-6 w-6">
            {userProfile?.avatar_url ? (
              <AvatarImage src={userProfile.avatar_url} alt="User avatar" />
            ) : null}
            <AvatarFallback>{getUserInitials()}</AvatarFallback>
          </Avatar>
          {!collapsed && (
            <div className="ml-2 overflow-hidden">
              <p className="text-sm font-medium truncate">{userProfile?.username}</p>
            </div>
          )}
        </div>
        <div>
          <Button
            variant="ghost"
            size="sm"
            className={cn(
              "flex text-red-500 hover:text-red-600 dark:text-red-400 dark:hover:text-red-300 transition-colors rounded-md",
              collapsed ? "py-2" : "py-1.5"
            )}
            onClick={logout}
          >
            <LogOut size={collapsed ? 20 : 18} />
            {!collapsed && <span className="ml-2">{t('logout')}</span>}
          </Button>
        </div>

      </div>
    </div>
  );
}
